<template>
  <a-card :bordered="false">

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="0">

          <a-col :md="6" :sm="24">
            <a-form-item label="网关名称">
              <a-input
                v-model="queryParam.gatewayName"
                allow-clear
                placeholder="请输入网关名称"/>
            </a-form-item>
          </a-col>

          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span
              class="table-page-search-submitButtons"
              style="padding-left: 16px;"
              :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" class="btn_search_reset" @click="$refs.table.refresh(true)"><a-icon
                type="search"/>查询</a-button>
            </span>
          </a-col>
          <a-col :md="!advanced && 10 || 24" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  style="float: right;">
                  <a-button
                    class="btn_add"
                    type="primary"
                    @click="addGrant"
                    >未授权网关</a-button>
                  <a-button
                    class="btn_add"
                    type="primary"
                    @click="handleSyncGrantStatus"
                    >同步授权状态</a-button>
                </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <div id="gatewayName">
      <s-table
        ref="table"
        size="default"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowKey="(record) => record.id"
        id="table-wrapper"
      >

      <span slot="status" slot-scope="text">
        {{ getStatus(text) }}
      </span>
        <span slot="gatewayName" slot-scope="text, record">
          <template v-if="text !== null">
            {{ record.gatewayName }}
          </template>
          <template v-if="text === null">
            未命名设备-{{ record.gatewayCode }}
          </template>
        </span>
        <span slot="grantStatus" slot-scope="text, record">
          <template v-if="text === '0'">待申请</template>
          <template v-if="text === '1'">待审核</template>
          <template v-if="text === '2'">审核通过</template>
          <template v-if="text === '3'">审核未通过</template>
          <template v-if="text === '4'">已过期</template>
        </span>

        <span slot="onlineStatus" slot-scope="text">
        {{ getOnlineStatus(text) }}
      </span>

        <span slot="dataReportingSwitch" slot-scope="text, record">
        <a-popconfirm placement="top" :title="text===0? '确定打开？':'确定关闭？'" @confirm="() => changeSwitch(record)">
          <a>{{ text === 1? '开':'关' }}</a>
        </a-popconfirm>
      </span>

        <span slot="action" slot-scope="text, record">
        <a @click="$refs.editInitGatewayForm.edit(record)" class="btn_edit">编辑</a>
        <a-divider type="vertical"/>
        <a-dropdown>
          <a class="btn_more"> 更多 <a-icon type="down"/></a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
                <a>删除</a>
              </a-popconfirm>
              <a @click="$refs.collectorIndexForm.toIndex(record)">参数配置</a>
              <a @click="$refs.channelIndexForm.toIndex(record)">通道设置</a>
              <a @click="$refs.gatewayConfigForm.toIndex(record)">网关配置</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown>

      </span>
      </s-table>
    </div>
    <edit-init-gateway-form ref="editInitGatewayForm" @ok="handleOk"/>
    <channel-index-form ref="channelIndexForm" @ok="handleOk"/>
    <collector-index-form ref="collectorIndexForm" @ok="handleOk"/>
    <gateway-config-form ref="gatewayConfigForm" @ok="handleOk"/>
    <grant-gateway-form ref="grantGatewayForm" @ok="handleOk"/>
  </a-card>
</template>

<script>
  import { STable } from '@/components'
  import { initGatewayPage, del, selfTest, changeSwitch, syncGatewayGrant } from '@/api/modular/main/bizgateway/bizGatewayManage'
  import editInitGatewayForm from './editInitGatewayForm'
  import { Empty } from 'ant-design-vue'
  import { treeList } from '@/api/modular/main/bizstation/bizStationManage'
  import channelIndexForm from './bizgatewaychannel/index'
  import collectorIndexForm from '@/views/main/bizcollectorconfig/index'
  import channelAddForm from './bizgatewaychannel/addForm'
  import gatewayConfigForm from '../bizgatewayconfigitem/index'
  import grantGatewayForm from './grantGatewayForm'
  import moment from 'moment'

  export default {
    components: {
      STable,
      editInitGatewayForm,
      channelIndexForm,
      channelAddForm,
      collectorIndexForm,
      grantGatewayForm,
      gatewayConfigForm
    },
    data () {
      return {
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {}, // 查询参数
        columns: [ // 表头
          {
            title: '网关名称',
            dataIndex: 'gatewayName',
            scopedSlots: { customRender: 'gatewayName' }
          },
          {
            title: '授权状态',
            dataIndex: 'grantStatus',
            scopedSlots: { customRender: 'grantStatus' },
            align: 'center'
          },
          {
            title: '网关状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'status' }
          },
          {
            title: '运行状态',
            dataIndex: 'onlineStatus',
            scopedSlots: { customRender: 'onlineStatus' }
          },
          {
            title: '设备IP',
            dataIndex: 'gatewayIp'
          },
          {
            title: '数据上报开关',
            dataIndex: 'dataReportingSwitch',
            scopedSlots: { customRender: 'dataReportingSwitch' }
          },
          {
            title: '创建日期',
            dataIndex: 'createdAt'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '180px',
            align:'center',
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return initGatewayPage(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        treeList: [],
        gatewayLoading: true,
        simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        treeLoading: true,
        stationId: ''
      }
    },

    methods: {
      del (record) {
        record.createdAt = moment(record.createdAt).format('YYYY-MM-DD HH:mm:ss')
        del(record).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        }).catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
      },
      addGrant () {
        this.$refs.grantGatewayForm.init()
      },
      getStatus (text) {
        if (text === 1) {
          return '开启'
        } else {
          return '禁用'
        }
      },
      getOnlineStatus (text) {
        if (text === 1) {
          return '在线'
        } else {
          return '离线'
        }
      },
      changeSwitch (record) {
        if (record.dataReportingSwitch === 1) record.dataReportingSwitch = 0
        else record.dataReportingSwitch = 1
        changeSwitch({ id: record.id, dataReportingSwitch: record.dataReportingSwitch }).then(res => {
          if (res.success) {
            this.$message.success('操作成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('操作失败：' + res.message)
          }
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      // 同步网关授权申请审核状态
      handleSyncGrantStatus(){
        syncGatewayGrant().then(res=>{
          if(res.success){
            this.$message.success('授权状态信息同步成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('授权状态信息同步失败：' + res.message)
          }
        })
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      handleClick (e) {
        this.stationId = e.toString()
        this.queryParam.stationId = e.toString()
        this.handleOk()
      },
      selfTest (record) {
        selfTest({ ip: record.gatewayIp }).then(res => {
          if (res.success) {
            this.$message.success(res.data)
          } else {
            this.$message.error(res.message)
          }
        })
      },
      isShow () {
        if (this.stationId) {
          return true
        }
        return false
      }
    }
  }
</script>

<style lang="less" scoped>
  /*@import '../~@/assets/css/list.less';*/
  .table-operator {
    margin-bottom: 18px;
  }
  #gatewayName .ant-table{
    height: 57vh !important;
  }
  button {
    margin-right: 8px;
  }

  .ant-tree li {
    overflow: no-content !important;
    white-space: pre-wrap !important;
  }
  .table-page-search-wrapper{
    .ant-row{
      margin-left: 0 !important;
    }
  }
</style>
